﻿using Comm;
using GalaSoft.MvvmLight.Messaging;
using Kinlo.Drv.Drv;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kinlo.Drv.Machine
{
    /// <summary>
    /// 锐捷RJ2903B
    /// </summary>
    public class RJShortCircuitMachine
    {
        #region 字段 
        RJShortCircuitDrv Tester;
        public string IP;
        public int Port;
        int TimeOut;
        public string ID;
        public string ResultToken = "ScanResultToken";
        byte[] startCmd = new byte[] { 0x7B, 0x00, 0x08, 0x02, 0x0F, 0xFF, 0x18, 0x7D };
        byte[] queryResultCmd = new byte[] { 0x7B, 0x00, 0x08, 0x02, 0xF0, 0x11, 0x0B, 0x7D };
        #endregion

        #region 方法
        public RJShortCircuitMachine(string ip, int port, int timeout)
        {
            this.IP = ip;
            this.Port = port;
            this.TimeOut = timeout;
            Tester = new RJShortCircuitDrv(IP, Port, TimeOut);
        }

        public bool Open()
        {
            return Tester.Open();
        }
        public bool Close()
        {
            return Tester.Disconnect();
        }

        byte CheckSum(string val)
        {
            var ascii = new System.Text.ASCIIEncoding();
            var asciis = ascii.GetBytes(val);
            int sum = 0;
            foreach (var a1 in asciis)
            {
                sum += a1 & 0xFF;
            }
            var sum1 = sum | 0x80;
            var checkSumCode = sum1.ToString("X4").Substring(2, 2);
            return Convert.ToByte(checkSumCode, 16);
        }

        public int Write(byte[] cmd)
        {
            return Tester.Write(cmd);
        }

        public byte[] Read()
        {
            return Tester.Read();
        }
        object locker = new object();
        /// <summary>
        /// 开始测试
        /// </summary>
        /// <returns></returns>
        public StartCmdResult TestStart()
        {
            var startCmdResult = new StartCmdResult();
            startCmdResult.Cmd = "FF";
            try
            {
                Write(startCmd);
                var result = Read();
                var msg = string.Format("短路测试仪启动原始值:{0}", string.Join(",", result));
                Logger.Info(msg);
                if (result != null && result.Length == 9)
                {
                    var r1 = result[0];
                    var r2 = result[result.Length - 1]; 
                    var rr1 = r1 == 0x7B;
                    var rr2 = r2 == 0x7D;


                    if (result[0] == 0x7B && result[result.Length - 1] == 0x7D)
                    {
                        var checkcode = 0;
                        for (var i = 1; i < result.Length - 2; i++)
                        {
                            checkcode += result[i];
                        }
                        var rrc = result[result.Length - 2].ToString("X8").Substring(6, 2);
                        var rrc1 = checkcode.ToString("X8").Substring(6, 2);
                        if (rrc == rrc1)
                        {
                            var resultcode = result[6].ToString("X2");
                            switch (resultcode)
                            {
                                case "00":
                                    startCmdResult.ResultCode = "00";
                                    startCmdResult.Msg = "测试启动成功";
                                    break;
                                case "01":
                                    startCmdResult.ResultCode = "01";
                                    startCmdResult.Msg = "测试启动失败 校验和错误";
                                    break;
                                case "02":
                                    startCmdResult.ResultCode = "02";
                                    startCmdResult.Msg = "测试启动失败 命令类型错误";
                                    break;
                                case "03":
                                    startCmdResult.ResultCode = "03";
                                    startCmdResult.Msg = "测试启动失败 命令字错误";
                                    break;
                                case "04":
                                    startCmdResult.ResultCode = "04";
                                    startCmdResult.Msg = "测试启动失败 状态不符";
                                    break;
                                case "05":
                                    startCmdResult.ResultCode = "05";
                                    startCmdResult.Msg = "测试启动失败 参数错误";
                                    break;
                            }
                        }
                        else
                        {
                            startCmdResult.ResultCode = "06";
                            startCmdResult.Msg = "测试启动失败 校验和错误";
                        }
                    }
                    else
                    {
                        startCmdResult.ResultCode = "07";
                        startCmdResult.Msg = "测试启动失败 数据接收异常";
                    }
                }
                return startCmdResult;
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("RJShortCircuitMachine TestStart {0}", ex.Message));
                startCmdResult.ResultCode = "08";
                startCmdResult.Msg = string.Format("测试启动失败 发生异常", ex.Message);
                return startCmdResult;
            }
        }
        /// <summary>
        /// 检索OK/NG结果
        /// </summary>
        /// <returns></returns>
        public TestVoteResult TestQueryResult()
        {
            var queryResult = new TestVoteResult();
            queryResult.Cmd = "11";
            try
            {
                Write(queryResultCmd);
                var result = Read();
                var msg = string.Format("短路测试仪查询原始值:{0}", string.Join(",", result)); 
                Logger.Info(msg);
                if (result != null && result.Length == 25)
                {
                    if (result[0] == 0x7B && result[result.Length - 1] == 0x7D)
                    {
                        var checkcode = 0;
                        for (var i = 1; i < result.Length - 2; i++)
                        {
                            checkcode += result[i];
                        }
                        var rrc = result[result.Length - 2].ToString("X8").Substring(6, 2);
                        var rrc1 = checkcode.ToString("X8").Substring(6, 2);
                        if (rrc == rrc1)
                        {
                            var resultcode = result[6].ToString("X2");
                            switch (resultcode)
                            {
                                case "00":
                                    queryResult.ResultCode = "00";
                                    queryResult.Msg = "查询结果成功";
                                    break;
                                case "01":
                                    queryResult.ResultCode = "01";
                                    queryResult.Msg = "查询结果失败 校验和错误";
                                    break;
                                case "02":
                                    queryResult.ResultCode = "02";
                                    queryResult.Msg = "查询结果失败 命令类型错误";
                                    break;
                                case "03":
                                    queryResult.ResultCode = "03";
                                    queryResult.Msg = "查询结果失败 命令字错误";
                                    break;
                                case "04":
                                    queryResult.ResultCode = "04";
                                    queryResult.Msg = "查询结果失败 状态不符";
                                    break;
                                case "05":
                                    queryResult.ResultCode = "05";
                                    queryResult.Msg = "查询结果失败 参数错误";
                                    break;
                            }
                            var r1 = result[6].ToString("X2") + result[7].ToString("X2");
                            var r2 = result[8].ToString("X2") + result[9].ToString("X2");
                            var r3 = result[10].ToString("X2") + result[11].ToString("X2");
                            var r4 = result[12].ToString("X2") + result[13].ToString("X2");
                            var r5 = result[14].ToString("X2");
                            var r6 = result[15].ToString("X2");
                            var r7 = result[16].ToString("X2");
                            var r8 = result[17].ToString("X2");
                            var r9 = result[18].ToString("X2");
                            var r10 = result[19].ToString("X2");
                            var r11 = result[20].ToString("X2");
                            var r12 = result[21].ToString("X2");
                            var r13 = result[22].ToString("X2");
                            //var r13 = "FF";
                            queryResult.Result1 = r1;
                            queryResult.Result2 = r2;
                            queryResult.Result3 = Convert.ToInt32(r3, 16).ToString();
                            queryResult.Result4 = (Convert.ToInt32(r4, 16)/10.0).ToString() ;
                            queryResult.Result5 = r5;
                            queryResult.Result6 = r6;
                            queryResult.Result7 = r7;
                            queryResult.Result8 = r8;
                            queryResult.Result9 = r9;
                            queryResult.Result10 = r10;
                            queryResult.Result11 = r11;
                            queryResult.Result12 = r12;
                            queryResult.Result13 = r13;
                        }
                        else
                        {
                            queryResult.ResultCode = "06";
                            queryResult.Msg = "查询结果失败 校验和错误";
                        }
                    }
                    else
                    {
                        queryResult.ResultCode = "07";
                        queryResult.Msg = "查询结果失败 数据接收异常";
                    }
                }
                else
                {
                    if (result[0] != 0x7B && result[result.Length - 1] != 0x7D)
                    {
                        var checkcode = 0;
                        for (var i = 1; i < result.Length - 2; i++)
                        {
                            checkcode += result[i];
                        }
                        var rrc = result[result.Length - 2].ToString("X8").Substring(6, 2);
                        var rrc1 = checkcode.ToString("X8").Substring(6, 2);
                        if (rrc == rrc1)
                        {
                            var resultcode = result[6].ToString("X2");
                            switch (resultcode)
                            {
                                case "01":
                                    queryResult.ResultCode = "01";
                                    queryResult.Msg = "查询结果失败 校验和错误";
                                    break;
                                case "02":
                                    queryResult.ResultCode = "02";
                                    queryResult.Msg = "查询结果失败 命令类型错误";
                                    break;
                                case "03":
                                    queryResult.ResultCode = "03";
                                    queryResult.Msg = "查询结果失败 命令字错误";
                                    break;
                                case "04":
                                    queryResult.ResultCode = "04";
                                    queryResult.Msg = "查询结果失败 状态不符";
                                    break;
                                case "05":
                                    queryResult.ResultCode = "05";
                                    queryResult.Msg = "查询结果失败 参数错误";
                                    break;
                            }
                        }
                        else
                        {
                            queryResult.ResultCode = "06";
                            queryResult.Msg = "查询结果失败 校验和错误";
                        }
                    }
                    else
                    {
                        queryResult.ResultCode = "07";
                        queryResult.Msg = "查询结果失败 数据接收异常";
                    }
                }
                return queryResult;
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("RJShortCircuitMachine TestStart {0}", ex));
                queryResult.ResultCode = "08";
                queryResult.Msg = string.Format("测试启动失败 发生异常", ex.Message);
                return queryResult;
            }
        }
        #endregion

        public class StartCmdResult
        {
            public string Cmd { get; set; }
            public string ResultCode { get; set; }
            public string Msg { get; set; }
        }

        public class TestVoteResult
        {
            public string Cmd { get; set; }
            public string ResultCode { get; set; }
            public string Msg { get; set; }
            /// <summary>
            /// 跌落1,(v)
            /// </summary>
            public string Result1 { get; set; }
            /// <summary>
            /// 跌落2,(v)
            /// </summary>
            public string Result2 { get; set; }
            /// <summary>
            /// VP电压,(v)
            /// </summary>
            public string Result3 { get; set; }
            /// <summary>
            /// 升压时间,为放大10倍后参数
            /// </summary>
            public string Result4 { get; set; }
            /// <summary>
            /// 开路结果（1字节，0表示无测试结果，1表示非OC状态，ff表示OC状态）
            /// </summary>
            public string Result5 { get; set; }
            /// <summary>
            /// 放电1结果FF为不合格，1为合格
            /// </summary>
            public string Result6 { get; set; }
            /// <summary>
            /// 放电2结果FF为不合格，1为合格
            /// </summary>
            public string Result7 { get; set; }
            /// <summary>
            /// VP 结果FF为不合格，1为合格
            /// </summary>
            public string Result8 { get; set; }
            /// <summary>
            /// 跌落1结果
            /// </summary>
            public string Result9 { get; set; }
            /// <summary>
            /// 跌落2结果
            /// </summary>
            public string Result10 { get; set; }
            /// <summary>
            /// TL结果
            /// </summary>
            public string Result11 { get; set; }
            /// <summary>
            /// TH结果
            /// </summary>
            public string Result12 { get; set; }
            /// <summary>
            /// 总结果FF为不合格，1为合格
            /// </summary>
            public string Result13 { get; set; }

            public override string ToString()
            {
                return string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}", 
                    Result1, Result2, Result3, Result4, Result5, Result6, Result7, Result8, Result8, Result9, Result10, Result11, Result12, Result13);
            }
        }
    }
}
